from werkzeug.security import generate_password_hash
from flask_jwt_extended import create_access_token
from app import db
from app.models import User

class AuthService:
    @staticmethod
    def register_user(username, email, password):
        if User.query.filter_by(username=username).first():
            raise ValueError('Username already exists')
        
        if User.query.filter_by(email=email).first():
            raise ValueError('Email already exists')
        
        user = User(username=username, email=email)
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        return user

    @staticmethod
    def login_user(username, password):
        user = User.query.filter_by(username=username).first()
        
        if not user or not user.check_password(password):
            raise ValueError('Invalid username or password')
        
        return create_access_token(identity=str(user.id))

    @staticmethod
    def reset_password(username, email, new_password):
        user = User.query.filter_by(username=username, email=email).first()
        
        if not user:
            return False
        
        user.set_password(new_password)
        db.session.commit()
        return True
